package org.example.leetcpde;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Comparator;

public class range {

    @Test
    void aa() {
//        int[][] aa = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] aa = {{2, 4}, {1, 6}};
        int[][] merge = merge(aa);
        System.out.println(11);

    }

    public int[][] merge(int[][] intervals) {
        int j = 0, len = intervals.length;
        if (len <= 1) {
            return intervals;
        }

        intervals = Arrays.stream(intervals).sorted(Comparator.comparingInt(o -> o[0])).toArray(int[][]::new);

        for (int i = 1; i < len; i++) {
            int[] former = intervals[j];
            int[] cur = intervals[i];
            int v11 = former[0], v12 = former[1], v21 = cur[0], v22 = cur[1];
            // 不相交
            if (v21 > v12 || v22 < v11) {
                intervals[++j] = cur;
                continue;
            }

            intervals[j] = new int[]{Math.min(v11, v21), Math.max(v12, v22)};
        }

        int[][] res = Arrays.copyOf(intervals, j + 1);
        return res;
    }
}
